#!/usr/bin/perl

use strict;
my %klb=read_klb('avp.klb');
my $total=0;
my $down='download.lst';
open DOWN,'>'.$down;

foreach (sort keys %klb)
{
#    print STDERR "$_\n";
  printf "Checking: %13s - ",$_;
  open FILE, "<$_" or (print(DOWN "$_\n"),print("$!\n"),next);
  my ($sig,$size)=@{$klb{$_}};
  my $rsize=(stat($_))[7];
  my $rsig;
  print "Size ",(($size == $rsize)?"OK ":"$rsize/$rsize ");
  $total+=$rsize;
  seek FILE,$rsize-60,0;
  read FILE,$rsig,58;
  close FILE;
  print "Checksum ",(($rsig ne $sig)?"\n$rsig\n$sig\n":"OK\n");
  print DOWN "$_\n" if (($rsig ne $sig) || ($size ne $rsize));
}
close DOWN;
if (-z $down){unlink $down}
#else {print `wget -Bhttp://updates2.kaspersky-labs.com/updates_x/ -i $down -N`}

while (<*.avc*>)
{
  next if exists $klb{$_};
  print "No reference to file '$_'\n";  
}

&update_time;
exit;

sub read_klb($)
{
  my %klb=();
  open KLB, "<$_[0]" or die "Can not open $_[0]: $!";
  while (<KLB>)
  {
    next unless /^\d+=([\w\.\-]+),([\w\+\/]+),(\d+),[\d\/]+\xD$/;
    print("Parsing $_[0], line $. Duplicating file $1\n"),next if exists $klb{$1};
    $klb{$1}=[$2,$3];
  }
  close KLB;
  %klb;
}
sub update_time()
{
my $last=`cat update.last`;$last=~s/^[\w\-]+: (.*?)\r?\n?$/$1/s;
my $lastt=(time-`date -d '$last' +%s`)/3600;
print "Updated: $last ";
if    ($lastt <   48 ) {printf "(%04.1f hours ago)",$lastt}
elsif ($lastt < 7*24 ) {printf "(%02u:%02u days:hours ago)",int($lastt/24),int($lastt)%24}
else  {printf "(%04.1f weeks ago)",$lastt/24/7}
printf " Size: %6ukb\n",$total/1024;
}